package com.guli.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.product.dao.PmsCategoryDao;
import com.guli.product.entity.PmsCategoryEntity;
import com.guli.product.service.PmsCategoryService;


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = this.page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<PmsCategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<PmsCategoryEntity> treelist() {
        /*List<PmsCategoryEntity> list = baseMapper.selectList(new QueryWrapper<PmsCategoryEntity>().eq("parent_cid", 0));
        for (PmsCategoryEntity cate : list) {
            List<PmsCategoryEntity> parent_cid = baseMapper.selectList(new QueryWrapper<PmsCategoryEntity>().eq("parent_cid", cate.getCatId()));
            cate.setChilder(parent_cid);
            for (PmsCategoryEntity pmsCategoryEntity : parent_cid) {
                List<PmsCategoryEntity> parent_cid1 = baseMapper.selectList(new QueryWrapper<PmsCategoryEntity>().eq("parent_cid", pmsCategoryEntity.getCatId()));
                pmsCategoryEntity.setChilder(parent_cid1);
            }
        }
        return list;*/

        List<PmsCategoryEntity> list = baseMapper.selectList(null);
        List<PmsCategoryEntity> l=list.stream().filter(item->{
            return item.getParentCid().equals(0L);
        }).map(item->{
            List<PmsCategoryEntity> li=gettree(list,item);
            item.setChilder(li);
            return item;
        }).sorted((item1,item2)->{
            return (item2.getSort()==null?0:item2.getSort())-(item1.getSort()==null?0:item1.getSort());
        }).collect(Collectors.toList());
        return l;
    }

    public List<PmsCategoryEntity> gettree(List<PmsCategoryEntity> all,PmsCategoryEntity pms){
        List<PmsCategoryEntity> a=all.stream().filter(item->{
            return item.getParentCid().equals(pms.getCatId());
        }).map(item->{
            List<PmsCategoryEntity> chiler=gettree(all,item);
            item.setChilder(chiler);
            return item;
        }).sorted((item1,item2)->{
            return (item2.getSort()==null?0:item2.getSort())-(item1.getSort()==null?0:item1.getSort());
        }).collect(Collectors.toList());
        return a;
    }

}